package cn.sdhuijin.vms.sms.callback;

import java.io.IOException;
import java.text.ParseException;
import java.util.Date;

import javax.inject.Inject;
import javax.swing.JOptionPane;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.smslib.AGateway;
import org.smslib.GatewayException;
import org.smslib.IInboundMessageNotification;
import org.smslib.InboundBinaryMessage;
import org.smslib.InboundMessage;
import org.smslib.Message.MessageTypes;
import org.smslib.Service;
import org.smslib.TimeoutException;
import org.springframework.stereotype.Component;

import cn.sdhuijin.vms.dao.ILeaveDao;
import cn.sdhuijin.vms.dao.IMessageDao;
import cn.sdhuijin.vms.dao.IPersonDao;
import cn.sdhuijin.vms.dao.IUserDao;
import cn.sdhuijin.vms.model.ApproveStatus;
import cn.sdhuijin.vms.model.Leave;
import cn.sdhuijin.vms.model.Message;
import cn.sdhuijin.vms.model.Person;
import cn.sdhuijin.vms.model.User;
import cn.sdhuijin.vms.sms.parser.ApproveToken;
import cn.sdhuijin.vms.sms.parser.LeaveToken;
import cn.sdhuijin.vms.sms.parser.MessageParser;
import cn.sdhuijin.vms.sms.parser.Token;
import cn.sdhuijin.vms.sms.util.SmsUtil;

@Component
public class InboundMessageNotification implements IInboundMessageNotification {
	final Logger logger = LoggerFactory
			.getLogger(InboundMessageNotification.class);
	@Inject
	private IPersonDao personDao;
	@Inject
	private IUserDao userDao;
	@Inject
	private ILeaveDao leaveDao;
	@Inject
	private IMessageDao messageDao;

	@Override
	public void process(AGateway gateway, MessageTypes msgType,
			InboundMessage msg) {
		logger.info(msg.toString());
		try {
			if (msg.getMemLocation().equals("SM")) {
				switch (msgType) {
				case INBOUND:
					processInbound(msg);
					break;
				case STATUSREPORT:
					logger.warn("状态报告:{}", msg);
					break;
				case UNKNOWN:
					logger.warn("未定义:{}", msg);
					break;
				case WAPSI:
					logger.warn("wap信息:{}", msg);
					break;
				default:
					break;
				}
			}

		} catch (Exception e) {
			logger.error("短信处理时发生错误:{}", e.toString());
		} finally {
			logger.debug("删除短信.");
			try {
				Service.getInstance().deleteMessage(msg);
			} catch (TimeoutException | GatewayException | IOException
					| InterruptedException e) {
				logger.error("删除短信时发生异常：{}", e.toString());
				e.printStackTrace();
			}
		}
	}

	/**
	 * 短信处理
	 * 
	 * @param msg
	 */
	private void processInbound(InboundMessage msg) {
		if (msg instanceof InboundBinaryMessage) {
			logger.warn("二进制短信：{}", msg);
		} else {

			// 话费通知
			if ("10010".equals(msg.getOriginator())) {
				String text = msg.getText();

				// 截止到2014年07月03日，您的帐户当月可用余额为-98.33元。
				String money = StringUtils.substringBetween(text, "为", "元");
				if (Float.valueOf(money) <= 10) {
					String[] phones = SmsUtil.notifyPhone.split(",");
					for (String p : phones) {
						SmsUtil.sendMessage(p, text);
					}

					JOptionPane.showMessageDialog(null, text, "短信猫余额提醒",
							JOptionPane.WARNING_MESSAGE);
				}
				logger.error("短信猫余额查询:话费剩余：{}元。内容：", money, text);
			}

			String phone = msg.getOriginator().substring(2);
			logger.debug("phone:{}", phone);
			Person person = personDao.findByPhone(phone);
			logger.debug("person:{}", person);
			User user = userDao.findByPhone(phone);
			logger.debug("user:{}", user);
			if (person != null || user != null) {
				try {
					Token t = MessageParser.parse(msg.getText());
					logger.debug("token:{}", t);
					if (t instanceof LeaveToken) {
						LeaveToken a = (LeaveToken) t;
						this.addLeave(person, a, msg);
					} else if (t instanceof ApproveToken) {
						ApproveToken a = (ApproveToken) t;
						logger.debug("leave.messageId={},agree:{}",
								((ApproveToken) t).getLeaveId(),
								((ApproveToken) t).getAgree());
						this.approve(user, a, msg);
					} else {
						logger.error("无法解析的短信内容:{}", msg.getText());

						String str = "内容：" + msg.getText()
								+ " 格式不正确，无法解析。请按照正确格式发送信息。";
						SmsUtil.sendMessage(msg.getOriginator().substring(2),
								str);

					}
				} catch (ParseException e) {
					e.printStackTrace();
				}
			}
		}
	}

	private void approve(User user, ApproveToken a, InboundMessage msg) {
		Leave leave = leaveDao.findByMasterIdAndMessageId(user.getId(),
				a.getLeaveId());
		if (leave != null) {
			leave.setApprovePerson(user);
			Message message = messageDao.save(new Message(user.getRealname(),
					msg.toString()));
			leave.setApproveMessage(message);
			leave.setApproveTime(new Date());
			leave.setStatus(a.getAgree() ? ApproveStatus.AGREE
					: ApproveStatus.DISAGREE);
			leaveDao.save(leave);
		} else {
			logger.debug("没找到申请 messageId={}", a.getLeaveId());
		}

	}

	private void addLeave(Person person, LeaveToken a, InboundMessage msg) {
		Leave leave = new Leave();
		leave.setStartTime(a.getStart());
		leave.setEndTime(a.getEnd());
		leave.setReason(a.getReason());
		leave.setPerson(person);
		Message message = messageDao.save(new Message(person.getName(), msg
				.toString()));
		leave.setLeaveMessage(message);
		leaveDao.save(leave);
	}

}
